//
//  NWComposeViewController.swift
//  Weibo01
//
//  Created by 牛威 on 15/12/15.
//  Copyright © 2015年 牛威. All rights reserved.
//

import UIKit
import SVProgressHUD

class NWComposeViewController: UIViewController {
    
    //MARK: - 取消按钮的监听方法
    
    @objc private func cancel(){
    
        //先关闭键盘
        
         textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
        
    
    }
    
    //MARK: - 发送微博方法
    
    @objc private func send(){
    
    
        //1获取文本内容
        
        let text = textView.emojiText
        
        //2调用网络方法
        
        //发送一个配图
        
//        let image = UIImage(named: "compose_app_empty")
        
        let image = pictureVC.pictures.last
        
        NetTools.shared.sendWBMethod(text,image: image) { (result, error) -> () in
            
            if error != nil {
                
              //提示用户网络慢
            
                SVProgressHUD.showInfoWithStatus("您的网络不给力,请重试")
              
                return
            
            }
            
//            print(result)
            self.cancel()
        }
        
        
        
    }
    
    //MARK: - 点击工具条按钮表情的监听方法
    
    @objc private func selectedPicture(){
        
        //首先退掉键盘
        
        textView.resignFirstResponder()
        
        //如果已经更新了约束就不需要再次更新了
        
        if pictureVC.view.frame.height > 0 {
        
        
          return
        
        }
    
    
        //更新布局
        
        pictureVC.view.snp_updateConstraints { (make) -> Void in
            
            make.height.equalTo(view.bounds.height * 0.6)
        }
        
        //这时snp中少用的一个方法,重新设置布局,把之前设置约束全都删除
        
        textView.snp_remakeConstraints { (make) -> Void in
           
            
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.bottom.equalTo(pictureVC.view.snp_top)


            
        }
        
        //解决图片选择突然跳出来(加一个动画效果)
        
        UIView.animateWithDuration(0.5) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
    }
    
    
    @objc private func selectedEmoticon(){
        
         //1先把默认键盘退出
        textView.resignFirstResponder()
        
        //2设置键盘(判断逻辑)
        
        textView.inputView = textView.inputView == nil ? emoji : nil
        
        //3重新激活键盘
        
        textView.becomeFirstResponder()
        
   
    
    }
    
    //MARK: - 监听键盘通知的方法
    
   @objc private func keyboardNotifify(notifiy:NSNotification){
    
//    print(notifiy)
    
   // UIKeyboardAnimationCurveUserInfoKey = 7;设置动画曲线解决跳跃问题
    
    let curve = (notifiy.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
    
    //    UIKeyboardAnimationDurationUserInfoKey = "0.25";
    //oc中数字在字典中是什么类型---->NSNumber
    
    let duration = (notifiy.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
    
    //   UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";

    //oc中字典中的结构体是什么类型
    
    let rect =  (notifiy.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
    
    //解决toolBar和键盘不能一起退下
    
    let offset = -UIScreen.mainScreen().bounds.height + rect.origin.y
    
    
    //更新约束
    
    toolBar.snp_updateConstraints { (make) -> Void in
        
        make.bottom.equalTo(view.snp_bottom).offset(offset)
    }
    
    //UIView的块动画,实质上是对核心动画(CAAnimaiton)的封装,底层还是调用的CAAnimaiton的方法
    
    UIView.animateWithDuration(duration) { () -> Void in
        
        //设置动画曲线解决toolBar的跳跃问题 一旦设置了动画  '7',动画时长就无效了,动画时长统一设置为0.5s
        
        
        UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
        
        //强制更新约束动画 看来来就流畅了
        self.view.layoutIfNeeded()
    }
    
 }
    
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        //添加键盘通知
        
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "keyboardNotifify:",
            name: UIKeyboardWillChangeFrameNotification,
            object: nil)
        
    }
    
    //MARK: - 销毁通知
    
    deinit {
    
    
       NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
    
    //MARK: - 激活键盘
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)
        
        if pictureVC.view.frame.height == 0 {
          
            textView.becomeFirstResponder()

        }
        
    }
    
    //MARK: - 视图生命周期
    
    override func loadView() {
        
        view = UIView()
        
        setupUI()
    }
    
    
    //MARK: - 懒加载控件
    
    ///照片选择控制器
    
    private lazy var pictureVC  = NWPictureCollectionVC()
   /// 表情键盘属性
    
    private lazy var emoji : EmojiView = EmojiView {[weak self] (emoji) -> () in
        
        self?.textView.insertEmoji(emoji)
    }

    /// 懒加载工具栏
    
    private lazy var toolBar = UIToolbar()
    
    ///  懒加载文本视图
    
    private lazy var textView : UITextView = {
    
    
     let v = UITextView()
        
        v.textColor = UIColor.darkGrayColor()
        
        v.font = UIFont.systemFontOfSize(18)
        
        //始终允许垂直滚动
        
        v.alwaysBounceVertical = true
        
        //拖拽关闭键盘(忽略这个警告)
        
        v.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        v.delegate = self
    
        return v
    }()
    
   //懒加载占位标签
    
    private lazy var placeHolder : UILabel = UILabel(title: "分享新鲜事...",
        fontSize: 18,
        color: UIColor.lightGrayColor())

}

//MARK: - UITextViewDelegate方法

extension  NWComposeViewController : UITextViewDelegate {


    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = true
        
        placeHolder.hidden = textView.hasText()
    }


}

//MARK: - 设置界面

private extension NWComposeViewController {

   
    
    //MARK: - 设置整体布局
    
      private func setupUI(){
        
        //取消自动调整滚动视图间距(+号按钮,离灰色的顶部太远了)
        
        automaticallyAdjustsScrollViewInsets = false
        
        view.backgroundColor = UIColor.whiteColor()
        //设置左右上角控件
        
        prepareNavigationBar()
    
       //设置titleView
        
        setupTitleView()
    
        //设置工具条
        
        setupToolBar()
        
        //设置文本框
        
        setupTextView()
        
        //设置照片选择
        
        setupPicture()
    }
    
    
    
    //MARK: - 设置选择照片控制器
    
    private func setupPicture(){
        
        
        //注意 :如果添加了子控制器,记住一定要添加addChildViewController
        
        
        addChildViewController(pictureVC)
        
        //添加控件
        
        view.addSubview(pictureVC.view)
        
        view.insertSubview(pictureVC.view, belowSubview: toolBar)
        
        //设置约束
        
        pictureVC.view.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(0)
        }
        
    
    
    }
    
    
    //MARK: - 设置navBar
    private func prepareNavigationBar(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        navigationItem.rightBarButtonItem?.enabled = false
    
    }
    //MARK: - 设置titleView
    private func setupTitleView(){
        
        //这里为什么写32 sb中默认两个控件的间距是8个点,我们15+13 = 28-32 =-4 这样看起来比较紧凑
    
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        
        
        navigationItem.titleView = titleView
        
        //实例化控件
        
        let titleLabel = UILabel(title: "发微博", fontSize: 15)
        let nameLabel = UILabel(title: UserAccountViewModel.sharedAccount.account?.screen_name ?? "" ,
            fontSize: 13,
            color: UIColor.lightGrayColor())
        
        //添加控件
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        //设置布局
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }

        nameLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)

        }
    
    }
    //MARK: - 设置toolBar
    private func setupToolBar(){
    
        //添加控件
        
        view.addSubview(toolBar)
        
        //处理➕号的阴影
        
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        //设置布局
        
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
    
        //添加按钮 compose_addbutton_background_highlighted
        
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectedPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName":"selectedEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            
            
            let item = UIBarButtonItem(pictureName: dict["imageName"]!, target: self, action: dict["actionName"])

            
            let it = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            
            items.append(item)
            items.append(it)
            
        
        }
        
        items.removeLast()
        
        toolBar.items = items
        
        
    }
    //MARK: - 设置文本框
    private func setupTextView(){
      
        //添加到视图
        
        view.addSubview(textView)
        
        //添加占位标签
        
        textView.addSubview(placeHolder)
        
        //设置约束
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolBar.snp_top)
            make.top.equalTo(self.snp_topLayoutGuideBottom)
        }
        
        placeHolder.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
        }
        
        
    
    
    
    }
    
    
    
    


}
